package xin.petstore.framework.web.img.servlet;

import com.eloancn.common.cache.RedisSpecMethods;
import com.eloancn.common.img.Cm;
import com.eloancn.common.img.ImageUtils;
import com.eloancn.common.img.dbmanager.ImgCodeRepositoryDao;
import com.eloancn.common.utils.IPUtils;
import com.eloancn.framework.cache.RedisService;
import com.eloancn.framework.cas.SessionUtils;
import com.eloancn.framework.utils.ObjectUtils;
import com.eloancn.framework.utils.SpringContextHolder;
import com.mongodb.gridfs.GridFSDBFile;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * =============================
 * Author: zsongbo
 * Function: 图片验证码
 * Version: 1.0
 * Date: 2016/7/4 0004
 * =============================
 */
public class VerificationCode extends HttpServlet implements Cm{
    public static final Logger logger = LoggerFactory.getLogger(VerificationCode.class);
    private ImgCodeRepositoryDao imgCodeRepositoryDao = SpringContextHolder.getBean("imgCodeRepositoryDao");
    private RedisService redisService = SpringContextHolder.getBean("redisService");
    private Random rand = new Random();
    private static final String tip = "Hi，你这是在玩嘻唰唰吗？慢点来吧！";
    private static final String errors = "加载出错了，请稍等会吧...";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	 response.setHeader("Cache-Control", "no-store");
         response.setHeader("Pragma", "no-cache");
         response.setDateHeader("Expires", 0L);
         response.setContentType("image/jpeg");
         response.addDateHeader("Last-Modified",System.currentTimeMillis()-86400);
         ServletOutputStream out = response.getOutputStream();
         StringBuffer buffer = new StringBuffer();
         List<byte[]> byteList = new ArrayList<byte[]>();
         String ipyuan = IPUtils.getRemoteAddr(request);
         try {
             String url = request.getRequestURI().toString();
             String lock_key = buffer.append(ipyuan).append("-").append(url).append("-").append(FLAG).toString();
             Object blackip =redisService.getObject(lock_key + BLACK_LIST);
             String ipCount = RedisSpecMethods.getValue(lock_key);
             if ( (ipCount != null && Integer.parseInt(ipCount.toString()) > COUNT_LIMIT) || ObjectUtils.isNotNullOrEmpty(blackip)) {
                 out.write(IOUtils.toByteArray(ImageUtils.tipForImages(tip, IMAGE_TYPE)));
                 out.flush();
                 out.close();
                 return;
             } else {
                 Long reqCount = RedisSpecMethods.incrBy(lock_key, TIME_LIMIT, 1);// 请求次数
                 if (reqCount > COUNT_LIMIT) {
                     redisService.setObject(lock_key + BLACK_LIST, lock_key, FORBIDEN_TIME_LIMIT, TimeUnit.SECONDS);
                     out.write(IOUtils.toByteArray(ImageUtils.tipForImages(tip, IMAGE_TYPE)));
                     out.flush();
                     out.close();
                     return;
                 }
             }
         } catch (Exception e) {
             logger.error("#验证码#缓存加载失败.", e );
             out.write(IOUtils.toByteArray(ImageUtils.tipForImages(errors, IMAGE_TYPE)));
             out.flush();
             out.close();
         }

         try {
             List filter = imgCodeRepositoryDao.getRandomList(4);
             List<GridFSDBFile> imgGridFSList = imgCodeRepositoryDao.getGridFSList(filter);
             System.out.println("#############################"+imgGridFSList.size());
             for (int i = 0; i < imgGridFSList.size(); i++) {
                 InputStream inputStream = imgGridFSList.get(i).getInputStream();
                 byteList.add(IOUtils.toByteArray(inputStream));
             }
             int ran = rand.nextInt(filter.size());
             SessionUtils.getSession().setAttribute("rand", ran+1);
             ByteArrayInputStream byteArrayInputStream = ImageUtils.waterMarkImage(byteList, IMAGE_TYPE, filter.get(ran).toString());
             out.write(IOUtils.toByteArray(byteArrayInputStream));
             out.flush();
             out.close();
         } catch (Exception e) {
             logger.error("#验证码#图片加载失败.", e );
         	 out.write(IOUtils.toByteArray(ImageUtils.tipForImages(errors, IMAGE_TYPE)));
              out.flush();
              out.close();
         }


    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

}